(function () {

	'use strict';

	angular
		.module('app')
		.controller('PaymentController', PaymentController);

	PaymentController.$inject = ['$scope', '$http', '$location', '$state', '$rootScope', '$timeout', '$stateParams', 'API', 'ENUM', 'PaymentModel'];

	function PaymentController($scope, $http, $location, $state, $rootScope, $timeout, $stateParams, API, ENUM, PaymentModel) {

        $scope.order_id = $stateParams.order_id;

		if (!$scope.order_id) {
			$timeout(function () {
				$rootScope.goHome();
			}, 1);
			return;
		}

		$scope.selectedType = null;
		$scope.paymentModel = PaymentModel;
        $scope.needPay = {};

		$scope.isSelected = function (type) {
            if (!$scope.selectedType) {
                return false;
            }
            if (type.code == $scope.selectedType.code) {
                return true;
            }
            return false;
        };

		$scope.touchSelect = function (type) {
            $scope.selectedType = type;
        };

		$scope.touchDetail = function() {
            $state.go('order-detail', {
                order_id: $scope.order_id
            });
        };

        $scope.touchSubmit = function () {
			if (!$scope.selectedType) {
				$scope.toast('请选择支持方式');
				return;
			}

			switch ($scope.selectedType.code) {
			case 'wxpay.web':
				{
					if ($rootScope.isWeixin()) {
						$state.go('wechat-pay', {
							order_id: $scope.order_id
						});
					} else {
						$scope.toast('暂不支持此方式');
					}
					break;
				}
			default:
				{
					$scope.toast('暂不支持此方式');
					break;
				}
			}
		}

		function _reload() {
			$scope.paymentModel.reload().then(function (succeed) {
				if (succeed) {
                    return API.order.getNeedPay({order_id: $scope.order_id}).then(function(res) {
                        if ( res ) {
                            $scope.needPay = res;
                        }
                    });
				}
			});
		}

		_reload();
	}

})();